<template>
  <ContentWrap>
    <view class="tableOp">
      <el-row type="flex" justify="end">
        <el-button style="" type="primary" @click="showAdd">
          <Icon class="mr-5px" icon="ep:plus" />{{ $t(`global.record`) }}
        </el-button>
      </el-row>
    </view>

    <el-table v-loading="loading" :data="list" :border="true" @row-click="admitDetails">
      <el-table-column type="index" />
      <el-table-column v-for="(item, index) in checkCol" :key="index" :prop="item.prop" :label="item.label"
        :width="item.width">
        <template #default="scope">
          <view @click.stop v-if="item.prop === 'tags'">
            <view class="flex flex-wrap">
              <el-tag v-for="item1 in scope.row.tags" :key="item1" class="tag">
                {{ item1 }}
              </el-tag>
            </view>
          </view>
          <view @click.stop style="display:flex;" v-if="item.prop === 'cardScanFilePath'">
            <el-popover placement="top-start" :width="200" trigger="hover">
              <el-image :src="scope.row.cardScanFilePath" style="width: 150px;height: 150px" />
<!--              <view style="margin-top: 50px;position: absolute;bottom: 5px;right: 10px">-->
<!--                <Icon class="mr-5px" icon="ep:download" />-->
<!--              </view>-->
              <template #reference>
                <el-image :preview-src-list="[scope.row.cardScanFilePath]" :src="scope.row.cardScanFilePath"
                  style="width: 50px; height: 50px" :z-index="20" :preview-teleported="true" />
              </template>
            </el-popover>
          </view>
          <view v-if="item.prop === 'customerGoodss'">
            <view class="flex flex-wrap">
              <el-tag v-for="tag in scope.row.customerGoodss" :key="tag" class="tag">
                {{ tag.goods }}
              </el-tag>
            </view>
          </view>
          <view v-if="item.prop === 'hislist'">
            <el-text @click="showAccess">
              <!--<Icon class="mr-5px" icon="ep:calendar" /> --> {{ scope.row.hislist?.length }}
            </el-text>
          </view>
          <view v-if="item.prop === 'receptionTime'">
            <el-text>
              {{ formatDate(scope.row.receptionTime) }}
            </el-text>
          </view>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <span @click.stop>
              <el-button link type="primary" @click="editDetails(scope.row)">
                <Icon class="mr-5px" icon="ep:edit" />
              </el-button>
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total"
      @pagination="getList" />
    <!-- <el-dialog v-model="showAdmitDetail" @closed="cacel" class="addDialog" top="8vh" width="80vw">
      <template #header>
        <el-row type="flex" justify="end">
          <el-button type="default">
            <Icon class="mr-5px" icon="ep:share" @click="shareLink" />分享
          </el-button>
          <el-button v-if="isEdit" type="danger" @click="deleteAdmit">
            <Icon class="mr-5px" icon="ep:delete" />删除
          </el-button>
        </el-row>
      </template>
      <el-form id="pdfDom" :model="admitInfo" ref="admitFormRef" label-position="top"
        style="height: 600px;overflow-y: auto;overflow-x: hidden;">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="自动编号">
              <el-text style="font-size: 24px;font-weight: 500">{{ admitInfo.id }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="接待时间">
              <el-date-picker v-model="admitInfo.receptionTime" type="datetime" :placeholder="$t(`global.select`)" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="名片扫描">
              <el-upload action="#" :file-list="fileDetailList" :auto-upload="false" :multiple="false"
                :show-file-list="false" :on-change="onchangeFile">
                <el-button style="width: 100%; font-weight: 600;" @click="scanCard">
                  <Icon class="mr-5px" icon="ep:postcard" />{{$t(`global.recognition`)}}
                </el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-collapse v-model="activeNames" style="margin-top: 30px">
          <el-collapse-item name="1">
            <template #title>
              <el-text class="form_sub_title">联系方式</el-text>
            </template>
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="姓名">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.name }}</span>
                  <el-input v-model="admitInfo.name" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职位">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.postion }}</span>
                  <el-input v-model="admitInfo.postion" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.phoneNumber }}</span>
                  <el-input v-model="admitInfo.phoneNumber" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="邮箱">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.email }}</span>
                  <el-input v-model="admitInfo.email" v-else />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template #title>
              <el-text class="form_sub_title">客户详情</el-text>
            </template>
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="公司名称">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.companyName }}</span>
                  <el-input v-model="admitInfo.companyName" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="姓名">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.name }}</span>
                  <el-input v-model="admitInfo.name" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职位">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.postion }}</span>
                  <el-input v-model="admitInfo.postion" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="固定电话">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.landlineTelephone }}</span>
                  <el-input v-model="admitInfo.landlineTelephone" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="手机">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.phoneNumber }}</span>
                  <el-input v-model="admitInfo.phoneNumber" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="邮箱">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.email }}</span>
                  <el-input v-model="admitInfo.email" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="地址">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.companyAddress }}</span>
                  <el-input v-model="admitInfo.companyAddress" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="公司网站">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.companyWebsite }}</span>
                  <el-input v-model="admitInfo.companyWebsite" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="admitInfo.cardScanFilePath">
                <el-form-item label="名片">
                  <el-image :preview-src-list="[admitInfo.cardScanFilePath]" :src="admitInfo.cardScanFilePath"
                    style="width: 300px;height:180px;" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template #title>
              <el-text class="form_sub_title">商品信息</el-text>
            </template>
            <el-row>
              <el-col :span="24">
                <el-form-item>
                  <proList v-model="admitInfo.customerGoodss" :readonly="!isAdd && !isEdit" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注">
                  <span v-if="!isEdit && !isAdd">{{ admitInfo.memo }}</span>
                  <el-input type="textarea" v-model="admitInfo.memo" v-else />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="4">
            <template #title>
              <el-text class="form_sub_title">交流总结</el-text>
            </template>
            <el-row>
              <el-col :span="24">
                <el-form-item label="标签">
                  <el-select v-model="admitInfo.tags" multiple filterable allow-create default-first-option
                    :reserve-keyword="false" placeholder="请选择标签" style="width: 100%" @change="addTag">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="交流总结" v-if="showAdmitDetail">
                  <span v-if="!isEdit && !isAdd" v-html="admitInfo.summary"></span>
            
                  <Editor v-model="admitInfo.summary" v-else :toolConfig="toolbarConfig" style="width: 100%"
                    height="300px" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="5">
            <template #title>
              <el-text class="form_sub_title">查看历史</el-text>
            </template>
            <el-table :data="viewList" :border="true">
              <el-table-column label="查看日期" prop="checkTime" />
              <el-table-column label="IP地址" prop="ip" />
              <el-table-column label="查看位置" prop="address" />
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <el-row type="flex" justify="center" style="margin-top: 20px">
        <el-button type="primary" v-if="isEdit || isAdd" @click="submitForm">{{ $t(`global.verify`) }}</el-button>
        <el-button @click="cacel">{{$t(`global.cancel`)}}</el-button>
      </el-row>
    </el-dialog> -->
  </ContentWrap>
</template>
<script lang="ts" setup>
import { FormInstance } from "element-plus";
import proList from '@/pages/hkb/components/proList/index.vue'
import * as admitApi from '@/service/api/hkb/admit/index'
import { ref } from 'vue'
import type { AdmitVO, ColumnVO, ViewListVO } from '../types'
import { createDictData, DictDataVO, getDictData, getDictDataPage } from "@/service/api/system/dict/dict.data";
import { goodsVO } from "../types";
import * as fileUpload from '@/service/api/infra/file'
import { useRouter } from 'vue-router';
import axios from 'axios';
import { createView } from "@/service/api/hkb/view";
import {getBusinessCardInfo} from "@/service/api/hkb/admit/index";
import { formatDate } from '@/utils/formatTime'
const router = useRouter()

const showDetail = ref(false)
const showAdmitDetail = ref(false)
const isAdd = ref(false) //是否新增
const isEdit = ref(false) //是否编辑
const childRef = ref()
const loading = ref(false) // 列表的加载中
const buttonLoading = ref(false) //按钮的加载
const total = ref(0) // 列表的总页数
const activeNames = ref(['2', '3', '4'])
const list = ref<AdmitVO[]>([]) // 列表的数据
const viewList = ref<ViewListVO[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileDetailList = ref<any[]>([])
const accessDetail = ref(false)
const message = useMessage() // 消息弹窗

const allCol = ref<ColumnVO[]>([
  { label: '自动编号', prop: 'id', width: '' },
  { label: '接待时间', prop: 'receptionTime', width: '' },
  { label: '标签', prop: 'tags', width: '200px' },
  { label: '公司名称', prop: 'companyName', width: '' },
  { label: '姓名', prop: 'name', width: '' },
  { label: '名片', prop: 'cardScanFilePath', width: '' },
  { label: '商品信息', prop: 'customerGoodss', width: '' },
  { label: '查看次数', prop: 'hislist', width: '' },
  { label: '创建人', prop: 'creator', width: '' }
])
const checkCol = ref<ColumnVO[]>([])
const checked = ref([])

const options = ref([])

const queryParams = ref({
  pageNum: 1,
  pageSize: 10
}) // 查询参数

const singleView = ref<ViewListVO>({
  checkTime: '',
  ip: '',
  address: '',
  viewType: '',
  sampleid: '',
})

const dictqueryParams = ref({
  pageNum: 1,
  pageSize: 100,
  dictType: 'hkb_admint_tag',
}) // 字典查询参数

const dictData = ref<DictDataVO>({
  dictType: 'hkb_admint_tag',
  label: '',
  value: '',
  status: 0,
  sort: 4,
})

import { IToolbarConfig } from '@wangeditor/editor'
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: [
    'uploadVideo', // 排除菜单组，写菜单组 key 的值即可
    "group-video",
    'group-image',
    'emotion',
    'todo',
    'insertLink',
    'insertTable',
    'divider',
    'codeBlock'
  ]
}

const admitFormRef = ref<FormInstance>()
const admitInfo = ref<AdmitVO>({
  id: '',
  automaticNumber: '',
  receptionTime: '',
  tags: [],
  companyName: '',
  landlineTelephone: '',
  phoneNumber: '',
  address: '',
  companyWebsite: '',
  name: '',
  postion: '',
  contactNumber: '',
  email: '',
  companyAddress: '',
  cardScanFileName: '',
  cardScanFilePath: '',
  cardScan: '',
  recordFileId: '',
  recordFileName: '',
  recordFilePath: '',
  memo: '',
  customerGoodss: [],
  summary: ''
})
const admitInfoInitForm = ref<AdmitVO>({
  id: '',
  automaticNumber: '',
  receptionTime: '',
  tags: [],
  companyName: '',
  landlineTelephone: '',
  phoneNumber: '',
  address: '',
  companyWebsite: '',
  name: '',
  postion: '',
  contactNumber: '',
  email: '',
  companyAddress: '',
  cardScanFileName: '',
  cardScanFilePath: '',
  cardScan: '',
  recordFileId: '',
  memo: '',
  recordFileName: '',
  recordFilePath: '',
  customerGoodss: [],
  summary: ''
})

const getList = async () => {
  const res = await admitApi.getList(queryParams.value)
  console.log(res)
  if (res.list.length > 0) {
    list.value = res.list
    total.value = res.total
  }
  getTagList()
}

const getTagList = async () => {
  const tagList = await getDictDataPage(dictqueryParams.value)
  if (tagList.total > 0) {
    options.value = tagList.list
  }
}

//新加标签
const addTag = () => {
  admitInfo.value.tags.map(item => {
    if (options.value.findIndex(o => o.value === item) < 0) {
      dictData.value.label = item
      dictData.value.value = item
      createDictData(dictData.value)
      getTagList()
    }
  })
}

/** 记录分享访问次数 **/
const countShare = async () => {
  let id = router.currentRoute.value.query.shareId
  if (id) {
    try {
      const response = await axios.get?.('https://qifu-api.baidubce.com/ip/local/geo/v1/district');
      singleView.value.checkTime = new Date()
      singleView.value.ip = response.data.ip
      singleView.value.address = response.data.data.prov + response.data.data.city + response.data.data.district
      singleView.value.viewType = '2'
      singleView.value.sampleid = id
    } catch (error) {
      console.error('请求错误', error);
      return null;
    }
    console.log(singleView)
    const res = await createView(singleView.value)
    let sharedPro = list.value.find(item => item.id === parseFloat(id))
    admitDetails(sharedPro)
  }
}

//提交接待
const submitForm = async () => {
  admitInfo.value.customerGoodss?.map(item => {
    item.qrcode = ''
    return item
  })
  admitFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (admitInfo.value.id) {
        await admitApi.editAdmit(admitInfo.value).finally(() => (buttonLoading.value = false));
      } else {
        console.log(admitInfo.value)
        await admitApi.addAdmit(admitInfo.value).finally(() => (buttonLoading.value = false));
      }
      showAdmitDetail.value = false;
      await getList();
    }
  })
}
/** 名片扫描 **/
const scanCard = () => {

}

/** 删除 **/
const deleteAdmit = async () => {
  try {
    // 二次确认
    await message.confirm('确认要立即删除这条数据吗?', '温馨提示')
    // 提交执行
    admitApi.deleteAdmit(admitInfo.value.id).then((res) => {
      if (res) {
        message.success('删除成功')
      } else {
        message.warning('删除失败')
      }
    }).finally(() => (cacel(), getList()))
  } catch (error) { }
}

//分享链接
const shareLink = async () => {

}
//详情
const admitDetails = (row) => {
  isEdit.value = false
  isAdd.value = false
  showAdmitDetail.value = true
  viewList.value = row?.hislist
  viewList.value.map(item => {
    item.checkTime = new Date(item.checkTime).toLocaleString()
    return item
  })
  admitInfo.value = row
}

const editDetails = (row) => {
  isEdit.value = true
  isAdd.value = false
  showAdmitDetail.value = true
  viewList.value = row?.hislist
  viewList.value.map(item => {
    item.checkTime = new Date(item.checkTime).toLocaleString()
    return item
  })
  admitInfo.value = row
}

/** 查看商品详情 **/
const proDetails = (row) => {
  isEdit.value = false
  isAdd.value = false
  showDetail.value = true
  childRef.value.initFormValue(row)
}

//显示新增
const showAdd = async () => {
  isEdit.value = false
  isAdd.value = true
  showAdmitDetail.value = true
}

const showAccess = () => {
  accessDetail.value = true
}

//关闭弹窗
const cacel = () => {
  showAdmitDetail.value = false
  accessDetail.value = false
  admitFormRef.value?.resetFields()
  admitInfo.value = JSON.parse(JSON.stringify(admitInfoInitForm.value))
  fileDetailList.value = []
}

/** 添加文件到文件列表 **/
const onchangeFile = async (file: any) => {
  fileDetailList.value.push(file)
  let formdata = new FormData()
  formdata.append('files', file.raw)
  const res = await fileUpload.updateFileBatch(formdata)
  let cardPath = import.meta.env.VITE_BASE_URL + '/admin-api/' + res.data[0].url
  let cardName = import.meta.env.VITE_BASE_URL + '/admin-api/' + res.data[0].name
  admitInfo.value.cardScanFilePath = cardPath
  admitInfo.value.cardScanFileName = cardName
  if(cardPath){
    let path = encodeURIComponent(cardPath)
    const res1 = await admitApi.getBusinessCardInfo(path)
    let data = JSON.parse(res1).result.item_list
    console.log(data)
    admitInfo.value.companyName = data.find(item => item.description === '公司').value
    admitInfo.value.companyAddress = data.find(item => item.description === '地址').value
    admitInfo.value.companyWebsite = data.find(item => item.description === '网址').value
    admitInfo.value.landlineTelephone = data.find(item => item.description === '电话').value
    admitInfo.value.name = data.find(item => item.description === '姓名').value
    admitInfo.value.postion = data.find(item => item.description === '职称').value
    admitInfo.value.phoneNumber = data.find(item => item.description === '手机').value
    admitInfo.value.email = data.find(item => item.description === '邮件').value
  }
}


/** 激活时 */
onActivated(() => {
  getList()
})

/** 初始化 **/
onMounted(async () => {
  countShare()
  await getList()
  checkCol.value = JSON.parse(JSON.stringify(allCol.value))
  checked.value = JSON.parse(JSON.stringify(allCol.value.map((item) => item.label)))
})

</script>
<style lang="scss" scoped>
.tableOp {
  margin-bottom: 10px;
}

.tag {
  margin: 5px 5px;
}

.form_sub_title {
  font-weight: 600;
}
</style>
